import { updateUserInfo, getCurrentUserInfo } from '../../../../utils/user-api';
import { areaList } from './areaData.js';
import Toast from 'tdesign-miniprogram/toast/index';

Page({
  data: {
    userInfo: {
      nickname: '',
      gender: 0,
      address: [],
    },
    addressText: '',
    addressVisible: false,
    provinces: [],
    cities: [],
    saving: false,
  },

  onLoad() {
    this.initAreaData();
    this.loadUserInfo();
  },

  /**
   * 加载用户信息
   */
  async loadUserInfo() {
    try {
      const result = await getCurrentUserInfo();
      
      if (result.success) {
        const userInfo = {
          nickname: result.data.nickname || '',
          gender: result.data.gender || 0,
          address: result.data.address || [],
        };
        
        this.setData({ userInfo }, () => {
          this.updateAddressText();
        });
      } else {
        Toast({
          context: this,
          selector: '#t-toast',
          message: result.message || '加载用户信息失败',
          theme: 'error'
        });
      }
    } catch (error) {
      console.error('加载用户信息失败:', error);
      Toast({
        context: this,
        selector: '#t-toast',
        message: '网络错误，请重试',
        theme: 'error'
      });
    }
  },

  /**
   * 初始化地区数据
   */
  initAreaData() {
    const provinces = this.getAreaOptions(areaList.provinces);
    const cities = provinces.length > 0 ? this.getCities(provinces[0].value) : [];
    this.setData({ provinces, cities });
  },

  getAreaOptions(data) {
    return Object.keys(data).map((key) => ({ 
      value: key, 
      label: data[key] 
    }));
  },

  getCities(provinceValue) {
    return this.getAreaOptions(areaList.cities).filter(
      (city) => `${city.value}`.slice(0, 2) === `${provinceValue}`.slice(0, 2)
    );
  },

  /**
   * 更新地址显示文本
   */
  updateAddressText() {
    const { address } = this.data.userInfo;
    if (address && address.length >= 2) {
      const provinceName = areaList.provinces[address[0]] || '';
      const cityName = areaList.cities[address[1]] || '';
      this.setData({
        addressText: `${provinceName} ${cityName}`.trim()
      });
    } else {
      this.setData({ addressText: '' });
    }
  },

  /**
   * 昵称修改
   */
  onNicknameChange(e) {
    this.setData({
      'userInfo.nickname': e.detail.value
    });
  },

  /**
   * 性别修改
   */
  onGenderChange(e) {
    this.setData({
      'userInfo.gender': parseInt(e.detail.value)
    });
  },

  /**
   * 显示地址选择器
   */
  showAddressPicker() {
    const { address } = this.data.userInfo;
    if (address && address.length > 0) {
      const cities = this.getCities(address[0]);
      this.setData({ cities });
    }
    this.setData({ addressVisible: true });
  },

  /**
   * 隐藏地址选择器
   */
  hideAddressPicker() {
    this.setData({ addressVisible: false });
  },

  /**
   * 地区选择器列改变
   */
  onAreaPick(e) {
    const { column, index } = e.detail;
    const { provinces } = this.data;

    if (column === 0) {
      const cities = this.getCities(provinces[index].value);
      this.setData({ cities });
    }
  },

  /**
   * 地址确认
   */
  onAddressChange(e) {
    const { value } = e.detail;
    this.setData({
      'userInfo.address': value,
      addressVisible: false
    }, () => {
      this.updateAddressText();
    });
  },

  /**
   * 保存个人信息
   */
  async onSaveInfo() {
    if (this.data.saving) return;

    const { userInfo } = this.data;

    // 简单验证
    if (!userInfo.nickname || !userInfo.nickname.trim()) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '请输入昵称',
        theme: 'warning'
      });
      return;
    }

    this.setData({ saving: true });

    try {
      // 提取城市名称
      let city = '';
      if (userInfo.address && userInfo.address.length >= 2) {
        city = areaList.cities[userInfo.address[1]] || '';
      }

      const updateData = {
        nickname: userInfo.nickname.trim(),
        gender: userInfo.gender,
        address: userInfo.address,
        city: city
      };

      const result = await updateUserInfo(updateData);

      if (result.success) {
        Toast({
          context: this,
          selector: '#t-toast',
          message: '保存成功',
          theme: 'success'
        });

        // 延迟返回上一页
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      } else {
        Toast({
          context: this,
          selector: '#t-toast',
          message: result.message || '保存失败',
          theme: 'error'
        });
      }
    } catch (error) {
      console.error('保存失败:', error);
      Toast({
        context: this,
        selector: '#t-toast',
        message: '网络错误，请重试',
        theme: 'error'
      });
    } finally {
      this.setData({ saving: false });
    }
  }
});
